package com.tevintao.marketingsystem.task;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.services.SmsContent;
import com.tevintao.marketingsystem.services.TaskLogicService;
import com.tevintao.marketingsystem.services.ViewOperation;
import com.tevintao.marketingsystem.xposted.WxTaskManger;

import java.util.Random;

import static com.tevintao.marketingsystem.services.SmsContent.getValidateCode;
import static com.tevintao.marketingsystem.services.TaskLogicService.INPUT_TYPE_BACK;
import static com.tevintao.marketingsystem.task.WxUiViewConfig.getViewByClassName;
import static com.tevintao.marketingsystem.task.WxUiViewConfig.getViewByIdAndContent;


/**
 * 自己人聊天
 */
public class AutoRegisterTaskProcess extends SetTaskExtra {
    private static AutoRegisterTaskProcess ourInstance = new AutoRegisterTaskProcess();

    public static AutoRegisterTaskProcess getInstance() {
        return ourInstance;
    }

    private AutoRegisterTaskProcess() {
    }

    private Random mRandom = new Random();
    private int mSelectPosition = -1;
    private String TelephoneNumberArea="+62";//选择注册的时候电话号码  所位于的国家区号   缅甸95  印尼62
    private int TelephoneNumberlenght=12;//选择注册的时候电话号码  的长度

    private boolean verificationcodeerror=false;//自动获取的验证码错误
    private boolean iftelephonenumnoeffect=false;//电话号码是否是无效的
    private EditText verificationcodeedit= null;
    private SmsContent mObserver;



    @SuppressWarnings("ResourceType")
    @Override
    public boolean processView(String contextName, View v) {
        LogManager.getInstance().logInfo("AutoRegisterTaskProcess processView contextName = " + contextName + " v = " + v.toString());
        WxUiViewConfig.printViewGroup((ViewGroup) v);
        if (WxUiViewConfig.MAIN_LAUNCH.equals(contextName)) {
            boolean inContact = WxUiViewConfig.inTab(v, WxUiViewConfig.TAB_ME);
            LogManager.getInstance().logInfo("intab = " + inContact);
            if (inContact) {
                LogManager.getInstance().logInfo("当前位于我按钮所在的列表");
                View setView = getViewByIdAndContent((ViewGroup) v, 16908310, "设置");
                if (null != setView) {
                    ViewOperation.clickView(setView);
                }
            }
        }else if ("com.tencent.mm.plugin.setting.ui.setting.SettingsUI".equals(contextName)) {
            View listView = v.findViewById(16908298);
            LogManager.getInstance().logInfo("listView = " + listView);
            if (null != listView && listView instanceof ListView) {
                ListView list = (ListView) listView;
                if (mSelectPosition < 0) {
                    mSelectPosition = list.getAdapter().getCount()-2;
                }
                int first = list.getFirstVisiblePosition();
                int last = list.getLastVisiblePosition();
                LogManager.getInstance().logInfo("mSelectPosition < 0 mSelectPosition = " + mSelectPosition + " first = " + first + " last =  " + last + " headerCount = " + list.getHeaderViewsCount() + "  " + list.getAdapter().getCount() + "  " + list.getCount() + " " + list.getFooterViewsCount());
                ViewOperation.moveListPosition(list, mSelectPosition);
                LogManager.getInstance().logInfo("移动到位");
            }
            View exitView = getViewByIdAndContent((ViewGroup) v, 16908310, "退出");
            if (null != exitView) {
                ViewOperation.clickView(exitView);
                LogManager.getInstance().logInfo("点击了退出  当前微信号码的 登陆");
            }
        } else if ("android.view.ContextThemeWrapper".equals(contextName)) {

            View registerView = getViewByIdAndContent((ViewGroup) v, 2131624112, "注册");
            View sendmessagesure = getViewByIdAndContent((ViewGroup) v, 2131626642, "确定");

            View verifycorderror = getViewByIdAndContent((ViewGroup) v, 2131625950, "验证码不正确，请重新输入");
            View verifycorderrorsure = getViewByIdAndContent((ViewGroup) v, 2131626642, "确定");

            View waitforverify = getViewByIdAndContent((ViewGroup) v, -1, "请稍候，我们正在验证你的手机号");

            View exitview = getViewByIdAndContent((ViewGroup) v,2131625950, "退出当前帐号后不会删除任何历史数据，下次登录依然可以使用本帐号。");
            View exitsure = getViewByIdAndContent((ViewGroup) v,2131626642, "退出");

            View regetcode = getViewByIdAndContent((ViewGroup) v,2131624112, "重新获取验证码");
            View regetvoivecode = getViewByIdAndContent((ViewGroup) v,2131624112, "语音获取验证码");

            View dotoomore = getViewByIdAndContent((ViewGroup) v,2131625950, "操作太频繁，请稍后再试");
            View dotoomoresure = getViewByIdAndContent((ViewGroup) v,2131626642, "确定");

            View laterregetverifycord = getViewByIdAndContent((ViewGroup) v,2131625950, "验证码短信可能略有延迟，确定取消并重新开始？");
            View waitregetverifycord = getViewByIdAndContent((ViewGroup) v,2131626641, "等待");
            View rebeginregetverifycord = getViewByIdAndContent((ViewGroup) v,2131626642, "重新开始");

            View errortelephonenum = getViewByIdAndContent((ViewGroup) v,2131626637, "手机号码错误");
            View noeffecttelephonenum  = getViewByIdAndContent((ViewGroup) v,2131625950, "你输入的是一个无效的手机号码");
            View errornoeffecttelephonenumsure = getViewByIdAndContent((ViewGroup) v,2131626642, "确定");

            if (null != errortelephonenum&&null != noeffecttelephonenum&&null != errornoeffecttelephonenumsure) {
                ViewOperation.clickView(errornoeffecttelephonenumsure);
                LogManager.getInstance().logInfo("确认了 输入的电话号码是无效的  不存在的  请重新输入");
                iftelephonenumnoeffect=true;
            }else if (null != laterregetverifycord&&null != waitregetverifycord&&null != rebeginregetverifycord) {
                ViewOperation.clickView(rebeginregetverifycord);
                LogManager.getInstance().logInfo("提示框：验证码短信可能略有延迟，确定取消并重新开始？      点击了重新开始注册");
            }else if (null != dotoomore&&null != dotoomoresure) {
                ViewOperation.clickView(dotoomoresure);
                taskError(v.getContext(), WxTaskManger.TASK_SATE_SUCCESS, "操作太频繁，请稍后再试    无法继续注册 结束了注册任务");
            }else if (null != regetcode&&null != regetvoivecode) {
                ViewOperation.clickView(regetcode);
                LogManager.getInstance().logInfo("点击了  重新获取验证码");
            }else if (null != exitsure&&null != exitview) {
                ViewOperation.clickView(exitsure);
                LogManager.getInstance().logInfo("点击了  确认退出按钮  退出当前微信号码");
            }else if (null != verifycorderror) {
                if (null != verifycorderrorsure)
                    ViewOperation.clickView(verifycorderrorsure);
                verificationcodeerror=true;
                LogManager.getInstance().logInfo("点击了  确定按钮   说明我知道  验证码输入错误了");
            }else if (null != waitforverify) {
                LogManager.getInstance().logInfo("请稍候，我们正在验证你的手机号  请耐心等待接收验证码");
            }else if (null != sendmessagesure) {
                ViewOperation.clickView(sendmessagesure);
                LogManager.getInstance().logInfo("点击了确定发送验证码到  所注册的手机号码上");
            }else if (null != registerView) {
                ViewOperation.clickView(registerView);
                LogManager.getInstance().logInfo("点击了注册按钮");
            }
            LogManager.getInstance().logInfo("~~~~~~~~~~~~~~~~~~~~~  -1");
        }else if ("com.tencent.mm.ui.account.LoginHistoryUI".equals(contextName)) {
            View moreView = getViewByIdAndContent((ViewGroup) v, 2131626249, "更多");
            if (null != moreView) {
                ViewOperation.clickView(moreView);
                LogManager.getInstance().logInfo("点击了查看更多按钮");
            }
        }
        else if ("com.tencent.mm.ui.account.RegByMobileRegAIOUI".equals(contextName)) {
            View nikenameview = v.findViewById(2131627271);
            ViewGroup nikename=(ViewGroup) nikenameview;
            View nameedit= nikename.getChildAt(1);
            EditText nikenameedit= (EditText)nameedit;

            View aeraview = v.findViewById(2131624400);
            TextView aeraedit= (TextView)aeraview;
            View aeratelephoneview = v.findViewById(2131626652);
            EditText telephoneedit= (EditText)aeratelephoneview;
            String telephoneString=telephoneedit.getText().toString();

            View password = getViewByClassName((ViewGroup) v, "MMVisiblePasswordEditText");
            EditText passwordedit= (EditText)password;

            if(iftelephonenumnoeffect==true){
                ViewOperation.setText(telephoneedit,"");
                ViewOperation.setText(passwordedit,"");
                LogManager.getInstance().logInfo("由于输入的电话号码是无效的  不存在的  把已经输入的错误电话号码和密码清空");
                iftelephonenumnoeffect=false;
            }

            if ("".equals(nikenameedit.getText().toString())) {
                LogManager.getInstance().logInfo("等待输入昵称");
                String[] str = new String[]{
                        "张三", "李四", "王五", "夜色", "月亮", "梦想", "奔跑", "kite", "watch", "fire"
                };
                ViewOperation.setText(nikenameedit, str[mRandom.nextInt(10)]);
            } else if (!TelephoneNumberArea.equals(aeraedit.getText().toString())){
                ViewOperation.setText(aeraedit,TelephoneNumberArea);
                LogManager.getInstance().logInfo("更改为电话号码  所属的国家区号");
            }else if ("".equals(telephoneString)) {
                LogManager.getInstance().logInfo("等待输入注册微信号  所使用的电话号码");
            }else if (!"".equals(telephoneString)&&telephoneString.length()==TelephoneNumberlenght&&"".equals(passwordedit.getText().toString())) {
                String passwordString = telephoneString.substring(telephoneString.length()-6,telephoneString.length());
                if("".equals(passwordedit.getText().toString()))

                    ViewOperation.setText(passwordedit,passwordString);
                LogManager.getInstance().logInfo("自动截取了 电话号码的  后6位为密码");
            }
            else if(!"".equals(nikenameedit.getText().toString())&&!"".equals(telephoneString)&&telephoneString.length()==TelephoneNumberlenght&&TelephoneNumberArea.equals(aeraedit.getText().toString())&&passwordedit.getText().toString().length()==6){
                //inputKeyBack(v.getContext());
                View registerView = getViewByIdAndContent((ViewGroup) v, 2131627276, "注册");
                if (null != registerView) {
                    ViewOperation.clickView(registerView);
                    LogManager.getInstance().logInfo("填写完微信信息后 点击了注册按钮");
                }
            }
        }else if ("com.tencent.mm.ui.account.mobile.MobileVerifyUI".equals(contextName)) {
            View nextStep = getViewByIdAndContent((ViewGroup) v, 2131625054, "下一步");
            View verificationcode = getViewByClassName((ViewGroup) v, "MMClearEditText");
            verificationcodeedit= (EditText)verificationcode;
            if (verificationcodeedit!=null) {
                if("".equals(verificationcodeedit.getText().toString())){
                    LogManager.getInstance().logInfo("请等待1分钟的时间  等待接收验证码");
                    //此处需要自动提取验证码的功能
                    mObserver = new SmsContent(v.getContext(), mHandler);
                    Uri uri = Uri.parse("content://sms");
                    //注册短信的监听
                    v.getContext().getContentResolver().registerContentObserver(uri, true, mObserver);

                    View noverificationcode = getViewByIdAndContent((ViewGroup) v, 2131626768, "收不到验证码？");
                    if(noverificationcode!=null&&noverificationcode.getVisibility()==View.VISIBLE){
                        ViewOperation.clickView(noverificationcode);
                        LogManager.getInstance().logInfo("点击了  收不到验证码？  按钮");
                    }
                }else{
                    View nexttoomore = getViewByIdAndContent((ViewGroup) v, 16908299, "操作太频繁，请稍后再试");
                    if(nexttoomore!=null&&nexttoomore.getVisibility()==View.VISIBLE){
                        LogManager.getInstance().logInfo("操作太频繁，请稍后再试   无法点击下一步了");
                        taskError(v.getContext(), WxTaskManger.TASK_SATE_SUCCESS, "操作太频繁，请稍后再试    无法点击下一步了 结束了注册任务");
                    }
                    else if (null != nextStep) {
                        if(verificationcodeerror==false) {
                            LogManager.getInstance().logInfo("下一步");
                            ViewOperation.clickView(nextStep);
                            LogManager.getInstance().logInfo("点击了下一步   继续进行微信号码的注册");
                        }else{
                            //验证码错误
                            LogManager.getInstance().logInfo("验证码错误  请重新提取验证码");
                            getValidateCode(v.getContext(), mHandler);
                        }
                    }
                }
            }
        }else if ("com.tencent.mm.ui.bindmobile.FindMContactAlertUI".equals(contextName)) {
            View back = v.findViewById(2131624160);
            LogManager.getInstance().logInfo("提示查看通讯录里边微信好友");
            if (null != back) {
                ViewOperation.clickView(back);
                LogManager.getInstance().logInfo("点击了返回按钮");//点击返回按钮没有反应  返回按钮无点击事件
                taskError(v.getContext(), WxTaskManger.TASK_SATE_SUCCESS, "注册微信成功  不再查看通讯录中使用微信的好友 直接结束任务");
            }
        }else if ("com.tencent.mm.ui.account.mobile.MobileLoginOrForceReg".equals(contextName)) {
            LogManager.getInstance().logInfo("提示此电话号码已经注册过微信了");
//            View nologin = getViewByIdAndContent((ViewGroup) v, 2131626766, "不是我的，继续注册");
//            View login = getViewByIdAndContent((ViewGroup) v, 2131626765, "是我的，立刻登录");
//            if (null != login) {
//                ViewOperation.clickView(login);
//                LogManager.getInstance().logInfo("点击了继续登陆");
//            }

            View back = v.findViewById(2131624159);
            if (null != back) {
                ViewOperation.clickView(back);
                LogManager.getInstance().logInfo("点击了返回按钮，返回注册页面");
                taskError(v.getContext(), WxTaskManger.TASK_SATE_SUCCESS, "此电话号码被使用过  已经注册过微信了  本次注册不成功 请更换没有注册过微信的电话号码");
            }
        }
        return false;
    }
    private void inputKeyBack(Context context) {
        Intent intent = new Intent(TaskLogicService.ACTION_KEY_RECEIVER);
        Bundle bundle = new Bundle();
        bundle.putInt(TaskLogicService.KEY_INPUT_KEY, INPUT_TYPE_BACK);
        intent.putExtras(bundle);
        context.sendBroadcast(intent);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == SmsContent.MSG_RECEIVED_CODE) {
                String code = (String) msg.obj;
                verificationcodeedit.setText(code);
                if(verificationcodeerror==true)
                    verificationcodeerror=false;
            }
        }
    };

}
